<?php
class SourcesController extends AppController
{
	var $name = "Sources";
	var $helpers = array('Ajax', 'Javascript');
	var $components = array('RequestHandler');

	function index()
	{
		$this->set('sources', $this->Source->find('all'));
	}
	
	function add()
	{
		if (!empty($_POST['sourceAddress']))
		{
			echo '<div style="color:red;">in process</div>';
			$newsource = array('Source' => array('address' => $_POST['sourceAddress'], 'search_pattern' => $_POST['sourceSearchPattern'], 'update_frequency' => $_POST['sourceUpdateFrequency']));
			if ($this->Source->save($newsource))
			{
				echo 'success, ID is: ' . $this->Source->id;
//				$this->redirect(array('action' => 'index'));
			}
			else
			{
				echo 'failed';
			}
			//echo $_POST['sourceUpdateFrequency'];
		}
	}
	
	function edit($id = null)
	{
		$this->Source->id = $id;
		if (!empty($_POST['sourceAddress']))
		{
			$this->data = $this->Source->read();
		}
		else
		{
			if ($this->Source->save($this->data))
			{
				$this->Session->setFlash('updated');
				$this->redirect(array('controller' => 'source', 'action' => 'index', $this->Source->id));
			}
		}
	}

	function request($url = null)
	{
		App::import('Core', 'HttpSocket');
		$HttpSocket = new HttpSocket();
		$results = $HttpSocket->get($url);

		if ($this->RequestHandler->isAjax())
		{
			$this->layout = 'ajax';
//			echo $results;
			echo htmlentities($results);
		}
		else
		{
			$this->set('url', $url);
			$this->set('results', htmlentities($results));
		}
	}
	
	function update()
	{
		$sources = $this->Source->find('all');
		foreach ($sources as $source)
		{
			echo $source['Source']['id'];
			echo '<br />';
		}
	}
}
?>
